﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using LPP.Service.SmsService;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using LPP.Service.UserRepository;
using LPP.Core.Jwt;
using System.Security.Claims;
using LPP.Entity.AppUser;

namespace LPP.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class SmsController : ControllerBase
    {
        private readonly SmsService _smsService;
        private readonly ILogger<SmsController> _logger;
        private readonly TokenManagement _tokenManagement;
        private readonly IUserService _userService;

        public SmsController(SmsService smsService, ILogger<SmsController> logger, IUserService userService, TokenManagement tokenManagement)
        {
            _smsService = smsService;
            _logger = logger;
            _userService = userService;
            _tokenManagement = tokenManagement;
        }

        // 发送验证码
        [HttpPost("send")]
        public async Task<IActionResult> SendSms([FromBody] SendSmsRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new
                {
                    message = "请求参数无效",
                    errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToArray()
                });
            }

            try
            {
                // 检查发送频率
                if (await _smsService.IsSendingTooFrequentAsync(request.PhoneNumber))
                {
                    return BadRequest(CreateErrorResponse("验证码发送过于频繁，请稍后再试"));
                }

                var result = await _smsService.SendVerificationCodeAsync(request.PhoneNumber);
                if (!result.Success)
                {
                    return BadRequest(CreateErrorResponse(result.Message));
                }

                _logger.LogInformation("验证码已发送到手机号 {PhoneNumber}", request.PhoneNumber);
                return Ok(CreateSuccessResponse(result.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "向手机号 {PhoneNumber} 发送验证码时发生错误", request.PhoneNumber);
                return StatusCode(500, CreateErrorResponse("发送验证码时发生错误"));
            }
        }

        [HttpPost("verify")]
        public async Task<IActionResult> VerifyCode([FromBody] VerifyCodeRequest request)
        {
            // 1. 验证验证码
            var verifyResult = await _smsService.VerifyCodeAsync(request.PhoneNumber, request.Code);
            if (!verifyResult.Success)
            {
                return BadRequest(new { message = verifyResult.Message });
            }

            // 2. 根据手机号获取用户信息
            var user = await _userService.GetUserByPhoneNumberAsync(request.PhoneNumber);
            if (user == null)
            {
                return NotFound(new { message = "用户未找到。" });
            }

            // 3. 检查用户是否被删除
            if (user.IsDelete)
            {
                return NotFound(new { message = "用户已被删除。" });
            }

            // 4. 生成新的 Token
            var token = GenerateJwtToken(user.UserID, request.PhoneNumber);

            // 5. 返回用户的 UserID 和 Token
            return Ok(new
            {
                success = true,
                user.UserID,
                token
            });
        }

        // 获取模型验证错误信息
        private string[] GetModelErrors()
        {
            return ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToArray();
        }

        // 响应封装类
        public class ApiResponse<T>
        {
            public bool Success { get; }
            public string Message { get; }
            public T Data { get; }

            public ApiResponse(bool success, string message, T data = default)
            {
                Success = success;
                Message = message;
                Data = data;
            }
        }

        // 成功响应封装
        private ApiResponse<string> CreateSuccessResponse(string message)
        {
            return new ApiResponse<string>(true, message);
        }

        // 错误响应封装
        private ApiResponse<string[]> CreateErrorResponse(string message, string[] errors = null)
        {
            return new ApiResponse<string[]>(false, message, errors);
        }

        // 请求 DTO 类
        public class SendSmsRequest
        {
            [Required(ErrorMessage = "手机号是必填项")]
            [Phone(ErrorMessage = "手机号格式不正确")]
            public string PhoneNumber { get; set; }
        }
      

        public class VerifyCodeRequest
        {
            [Required(ErrorMessage = "手机号是必填项")]
            [RegularExpression(@"^1[3-9]\d{9}$", ErrorMessage = "手机号格式不正确")]
            public string PhoneNumber { get; set; }

            [Required(ErrorMessage = "验证码是必填项")]
            [StringLength(6, MinimumLength = 6, ErrorMessage = "验证码必须是6位")]
            public string Code { get; set; }
        }

        // 生成 JWT Token
        private string GenerateJwtToken(int userId, string phoneNumber)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Sid, userId.ToString()),
                new Claim(ClaimTypes.Name, phoneNumber)
            };
            return JwtHelper.CreateToken(claims, _tokenManagement);
        }
    }
}
